require 'mina/bundler'
require 'mina/rails'
require 'mina/git'
require 'mina/multistage'
require 'mina/puma'
require 'mina_sidekiq/tasks'
# require 'mina/rbenv'  # for rbenv support. (https://rbenv.org)
require 'mina/rvm'    # for rvm support. (https://rvm.io)

set :rvm_use_path, '/usr/local/rvm/scripts/rvm'

set :shared_dirs, %W(public/uploads public/theme tmp/pids tmp/sockets vendor/bundle log)
set :shared_files, %W(config/database.yml config/secrets.yml config/puma.rb config/settings/production.local.yml config/schedule.rb)

# task :test do
#   comment 'Start sidekiq'
#   command %[echo "this is a  test"]
#   comment %(mkdir -p "#{fetch(:deploy_to)}/shared/pids/")
#   comment %(mkdir -p "#{fetch(:deploy_to)}/shared/log/")
# end

task :setup do
  # sidekiq needs a place to store its pid file and log file 配置sidekiq的pids和log目录
  command %(mkdir -p "#{fetch(:deploy_to)}/shared/pids/")
  command %(mkdir -p "#{fetch(:deploy_to)}/shared/log/")

  command %[mkdir -p "#{fetch(:shared_path)}/log"]
  command %[chmod g+rx,u+rwx "#{fetch(:shared_path)}/log"]

  command %[mkdir -p "#{fetch(:shared_path)}/tmp/pids"]
  command %[mkdir -p "#{fetch(:shared_path)}/tmp/sockets"]
  # 在服务器项目目录的shared中创建config文件夹 下同
  command %[mkdir -p "#{fetch(:shared_path)}/config"]
  command %[mkdir -p "#{fetch(:shared_path)}/vendor/bundle"]
  command %[mkdir -p "#{fetch(:shared_path)}/config/settings"]
  command %[chmod g+rx,u+rwx "#{fetch(:shared_path)}/config"]
  command %[chmod g+rx,u+rwx "#{fetch(:shared_path)}/config/settings"]

  command %[mkdir -p "#{fetch(:shared_path)}/public/uploads"]
  command %[mkdir -p "#{fetch(:shared_path)}/public/uploads/excel"]
  command %[mkdir -p "#{fetch(:shared_path)}/public/uploads/tmp"]

  command %[touch "#{fetch(:shared_path)}/config/database.yml"]
  command %[touch "#{fetch(:shared_path)}/config/puma.rb"]
  # command %[touch "#{fetch(:shared_path)}/config/bluepill.rb"]
  command %[touch "#{fetch(:shared_path)}/config/secrets.yml"]
  command %[touch "#{fetch(:shared_path)}/config/schedule.rb"]
  command %[touch "#{fetch(:shared_path)}/config/settings/production.local.yml"]

  command %[echo "-----> Be sure to edit '#{fetch(:shared_path)}/config/database.yml'."]
  command %[echo "-----> Be sure to edit '#{fetch(:shared_path)}/config/puma.rb'."]
  command %[echo "-----> Be sure to edit '#{fetch(:shared_path)}/config/secrets.yml'."]
  command %[echo "-----> Be sure to edit '#{fetch(:shared_path)}/config/schedule.rb'."]
  command %[echo "-----> Be sure to edit '#{fetch(:shared_path)}/config/settings/production.local.yml'."]
end

desc "Deploys the current version to the server."
task :deploy do
  deploy do
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'deploy:cleanup'

    on :launch do
      invoke :'puma:restart'
    end
  end
end
